package com.service.lims;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.lims.TestDao;
import com.dao.store.MergeDao;
import com.model.lims.TestModel;
import com.model.store.MergeModel;
import com.model.sys.SysDict;
import com.model.sys.SysUser;
import com.service.sys.SysDictService;

@Service("limsTestService")
public class TestService {
	static final Logger logger = LoggerFactory.getLogger(TestService.class);

	@Autowired
	TestDao testDao;
	@Autowired
	com.service.external.lims.TestService limTestService;
	@Autowired
	MergeDao mergeDao;
	@Autowired
	SysDictService sysDictService;

	@SuppressWarnings("unchecked")
	public HttpResult selectLimsList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		int pageNum = Integer.parseInt(queryMap.get("pageNum").toString());
		int pageSize = Integer.parseInt(queryMap.get("pageRows").toString());
		String tankNum = queryMap.get("status").toString();

		HashMap<String, Object> dicHashMap = new HashMap<String, Object>();
		dicHashMap.put("dicName", tankNum);
		List<SysDict> sysDicts = sysDictService.queryItemByTypeName(dicHashMap);
		String testItems = "";
		if (sysDicts.size() > 0) {
			testItems = sysDicts.stream().map(SysDict::getDicValue).collect(Collectors.joining("','", "'", "'"));
		}

		List<MergeModel> mergeModels = mergeDao.selectList(null);
		String tandString = mergeModels.stream().map(MergeModel::getTankNum)
				.collect(Collectors.joining("','", "'", "'"));
		String ordNo = limTestService.getTestOrdNo(tankNum, queryMap.get("startTime").toString(),
				queryMap.get("endTime").toString(), tandString);

		List<TestModel> list = (List<TestModel>) limTestService
				.getTestRes(tankNum, queryMap.get("startTime").toString(), queryMap.get("endTime").toString(), pageNum,
						pageSize, tandString, ordNo, testItems)
				.getData();

		BigDecimal count = (BigDecimal) limTestService.getTestResCount(tankNum, queryMap.get("startTime").toString(),
				queryMap.get("endTime").toString(), pageNum, pageSize, tandString, ordNo, testItems).getData();

		httpResult.setRows(list);
		httpResult.setTotal(count.intValue());
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<TestModel> list = testDao.selectList(queryMap);
		int count = testDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String ordNo, String sampDate, String tankNum, String productNo, String testAnalyte) {
		HttpResult httpResult = new HttpResult();
		TestModel testModel = testDao.load(ordNo, sampDate, tankNum, productNo, testAnalyte);
		httpResult.setData(testModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(TestModel testModel) {
		if (testModel == null) {
			return HttpResult.error("参数不能为空");
		}
		HttpResult httpResult = new HttpResult();
		int result = 0;
		if (!StringUtils.isNotNull(testModel.getOrdNo())) {
			testModel.setOrdNo(UUID.randomUUID().toString());
			result = testDao.insert(testModel);
		} else {
			result = testDao.update(testModel);
		}
		if (!StringUtils.isNotNull(testModel.getSampDate())) {
			testModel.setSampDate(UUID.randomUUID().toString());
			result = testDao.insert(testModel);
		} else {
			result = testDao.update(testModel);
		}
		if (!StringUtils.isNotNull(testModel.getTankNum())) {
			testModel.setTankNum(UUID.randomUUID().toString());
			result = testDao.insert(testModel);
		} else {
			result = testDao.update(testModel);
		}
		if (!StringUtils.isNotNull(testModel.getProductNo())) {
			testModel.setProductNo(UUID.randomUUID().toString());
			result = testDao.insert(testModel);
		} else {
			result = testDao.update(testModel);
		}
		if (!StringUtils.isNotNull(testModel.getTestAnalyte())) {
			testModel.setTestAnalyte(UUID.randomUUID().toString());
			result = testDao.insert(testModel);
		} else {
			result = testDao.update(testModel);
		}
		if (result > 0) {
			httpResult.setMsg(testModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(testModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(testModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 提交
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult commit(TestModel testModel) {
		if (testModel == null) {
			return HttpResult.error("参数不能为空");
		}
		testModel.setStatus(Global.YES + "");
		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = testDao.update(testModel);
		result = testDao.update(testModel);
		result = testDao.update(testModel);
		result = testDao.update(testModel);
		result = testDao.update(testModel);
		if (result > 0) {
			httpResult.setMsg(testModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(testModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(testModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult delete(TestModel testModel) {
		if (!StringUtils.isNotNull(testModel.getOrdNo()) || !StringUtils.isNotNull(testModel.getSampDate())
				|| !StringUtils.isNotNull(testModel.getTankNum()) || !StringUtils.isNotNull(testModel.getProductNo())
				|| !StringUtils.isNotNull(testModel.getTestAnalyte())) {
			return HttpResult.error("参数不能为空");
		}
		TestModel model = testDao.load(testModel.getOrdNo(), testModel.getSampDate(), testModel.getTankNum(),
				testModel.getProductNo(), testModel.getTestAnalyte());
		if (model == null) {
			return HttpResult.error("无数据！");
		}
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = testDao.delete(testModel.getOrdNo(), testModel.getSampDate(), testModel.getTankNum(),
				testModel.getProductNo(), testModel.getTestAnalyte());
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 撤回
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult back(String ordNo, String sampDate, String tankNum, String productNo, String testAnalyte) {
		if (!StringUtils.isNotNull(ordNo) || !StringUtils.isNotNull(sampDate) || !StringUtils.isNotNull(tankNum)
				|| !StringUtils.isNotNull(productNo) || !StringUtils.isNotNull(testAnalyte)) {
			return HttpResult.error("参数不能为空");
		}
		TestModel model = testDao.load(ordNo, sampDate, tankNum, productNo, testAnalyte);

		// todo

		HttpResult httpResult = new HttpResult();
		model.setStatus(Global.NO + "");
		int result = testDao.update(model);
		if (result > 0) {
			httpResult.setMsg("撤回成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<TestModel> list = testDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), TestModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
